package com.kakavr.wxpay.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.kakavr.base.controller.BaseController;
import com.kakavr.pay.constant.WxConstant;
import com.kakavr.result.Result;
import com.kakavr.wxpay.service.IWXPayService;

@RestController
@RequestMapping("n/wxpay")
public class WXPayController extends BaseController {
	@Resource
	private IWXPayService wXPayService;

	/**
	 * 微信支付回调
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "wxpayNotify", method = RequestMethod.POST)
	public void notifyWXPay(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		debug("微信后端通知===================================---begin");
		BufferedReader in = null;
		InputStream inputStream = null;
		StringBuffer sb = new StringBuffer();
		try {
			String s = null;
			inputStream = request.getInputStream();
			in = new BufferedReader(new InputStreamReader(inputStream,
					WxConstant.CHARSET));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			String sbStr = sb.toString();
			info("微信支付后端返回结果：" + sbStr);
			if (StringUtils.isNotBlank(sbStr)) {
				if (wXPayService.updateWXpayLogByNotify(sbStr)) {
					String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
					Result.outText(resXml, response);
				}
			}
		} catch (Exception e) {
			error("读取微信返回信息流出错，错误信息：" + e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				error(e.getMessage());
			}
		}
		String resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[通知签名验证失败]]></return_msg></xml> ";
		Result.outText(resXml, response);
		debug("微信后端通知===================================---end");
	}

}
